package coms.ejb.sessionbean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;

import coms.dataaccess.DAOFactory;
import coms.dataaccess.FileItemDAO;
import coms.dataaccess.ReviewDao;
import coms.datatransfer.ConferenceItemDTO;
//import coms.datatransfer.AssignedReviewDTO;
import coms.datatransfer.FileItemDTO;
import coms.datatransfer.ReviewDTO;
import coms.datatransfer.UserDTO;

@Stateless(name = "FileBean", mappedName = "FileBean")
@Remote(FileBeanRemote.class)
public class FileBean implements FileBeanRemote, Serializable {

	private FileItemDAO fileItemDAO = null;
	
	public FileBean(){}
	
    public void ejbCreate() {
    	fileItemDAO = DAOFactory.getInstance().getFileItemDAO();
    }
	
    @Override
    public void insertFileItem(FileItemDTO fileItem) {
    	System.out.println("inside insert file item");
    	fileItemDAO.insertFileItem(fileItem);
	}
    
    @Override
	public FileItemDTO findFileItemById(int fileItemID) {
    	
    	return fileItemDAO.findFileItemById(fileItemID);
    }
    
    @Override
   	public List<FileItemDTO> getFilesByReview (List<ReviewDTO> reviewList) {
    	
    	
    	List<FileItemDTO> filesList = new ArrayList<FileItemDTO>();
    	for (ReviewDTO r : reviewList)
    	{
    		filesList.add(findFileItemById(r.getFileID()));
    		
    	}
       	
       	return filesList;
    }
    
    public List<FileItemDTO> findFileItemByConfItem(int conferenceItemId) throws Exception{
		List<Object[]> fileItems = fileItemDAO.findFileByConferenceItemId(conferenceItemId);
		List<FileItemDTO> fileItemList = new ArrayList<FileItemDTO>();
		for (Object[] r: fileItems)
		{
			fileItemList.add((FileItemDTO)r[0]);
		}
		return fileItemList;
		
	}
    
    @SuppressWarnings("unchecked")
	public void assignReviewers(ArrayList<UserDTO> reviewerList, int fileid) throws Exception{
    	
    	Set<UserDTO> reviewSet = new HashSet<UserDTO>();
    	
    	FileItemDTO fileItemDTO = fileItemDAO.findFileItemById(fileid);
    	//fileItemDTO.getListOfReviewers();
    	for(UserDTO u: reviewerList){
    	Boolean f = false;
    	for(UserDTO r: fileItemDTO.getListOfReviewers()){
    		
    		if(u.getUserID() == r.getUserID())
    			f=true;
    		
    	}
    	if(f== false)
    	reviewSet.add(u);
    	}
    	System.out.println(fileItemDTO.getListOfReviewers().size());
    	System.out.println(reviewSet.size());
    	fileItemDTO.getListOfReviewers().addAll(reviewSet);
    	System.out.println(fileItemDTO.getListOfReviewers().size());
    	fileItemDAO.updateFileItem(fileItemDTO);
    }
	
}
